package com.org.web.handle.wechat.service;

import com.alibaba.fastjson.JSONObject;
import com.org.platform.utils.CommonUtil;
import com.org.web.handle.wechat.WechatCommon;
import java.io.UnsupportedEncodingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author devg
 * @Date 2020/3/6 14:26
 */

@Slf4j
@Service
public class WechatService {

  @Value("${wechat.appId}")
  private String appId;

  @Value("${wechat.secret}")
  private String secret;

  @Autowired
  private RestTemplate restTemplate;

  public JSONObject getAccessToken(String code){
    JSONObject resultJson = new JSONObject();
    if(CommonUtil.isEmpty(code)){
      return resultJson;
    }
    String url = WechatCommon.accessTokenUrl +"?appid="+appId+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
    String result = restTemplate.getForObject(url,String.class); // 通过code 获取 access_token
    log.info("accessTokenUser:{}",result);
    return JSONObject.parseObject(result);
  }

  /**
   *  刷新token
   * @param refreshToken
   * @return
   */
  public JSONObject getRefreshAccessToken(String refreshToken){
    JSONObject resultJson = new JSONObject();
    if(CommonUtil.isEmpty(refreshToken)){
      return resultJson;
    }
    String url = WechatCommon.refreshAccessTokenUrl+"?appid="+appId+"&grant_type=refresh_token&refresh_token="+refreshToken;
    String result = restTemplate.getForObject(url,String.class);
    log.info("refreshTokenUser:{}",result);
    return JSONObject.parseObject(result);
  }

  /**
   * 通过access_token,openid 获取用户信息
   * @param accessToken
   * @param openId
   * @return
   */
  public JSONObject getUserInfo(String accessToken,String openId){
    String url = WechatCommon.userInfo+"?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
    String result = restTemplate.getForObject(url,String.class);
    try{
      result = new String(result.getBytes("ISO-8859-1"), "UTF-8");
    }catch (UnsupportedEncodingException ex){
      log.error(ex.getMessage());
    }
    JSONObject jsonObject = JSONObject.parseObject(result);
    return jsonObject;
  }
}



/*  http demo
    HttpHeaders httpHeaders = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
    httpHeaders.setContentType(type);
    Map<String, Object> map = new HashMap<>();
    HttpEntity<Map<String, Object>> objectHttpEntity = new HttpEntity<>(map,httpHeaders);
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,objectHttpEntity,String.class);
   ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
   String result = responseEntity.getBody();
   */
